package org.linlinjava.litemall.admin.web;

import com.github.pagehelper.PageInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.admin.annotation.LoginAdmin;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallMechanism;
import org.linlinjava.litemall.db.domain.LitemallMechanismGoods;
import org.linlinjava.litemall.db.domain.LitemallMechanismGoodsCheck;
import org.linlinjava.litemall.db.domain.LitemallMechanismVo2;
import org.linlinjava.litemall.db.service.LitemallGoodsService;
import org.linlinjava.litemall.db.service.LitemallMechanismGoodsCheckService;
import org.linlinjava.litemall.db.service.LitemallMechanismGoodsService;
import org.linlinjava.litemall.db.service.LitemallMechanismService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/auditing")
public class MechanismGoodsCheckController {
    private final Log logger = LogFactory.getLog(MechanismGoodsCheckController.class);
    @Autowired
    private LitemallMechanismGoodsCheckService mechanismGoodsCheckService;
    @Autowired
    private LitemallMechanismGoodsService goodsService;
    @Autowired
    private LitemallMechanismService mechanismService;

    @Autowired
    private PlatformTransactionManager txManager;

    @GetMapping("/list")
    public Object list(@LoginAdmin Integer adminId,
        @RequestParam(value = "page", defaultValue = "1") Integer page,
        @RequestParam(value = "limit", defaultValue = "10") Integer limit,
        Byte value,String sort, String order){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }
        //查询check表数据和数量
        List<LitemallMechanismGoodsCheck> list = mechanismGoodsCheckService.querySelective(page, limit,value, sort, order);
        long total = PageInfo.of(list).getTotal();

        Map<String, Object> data = new HashMap<>();
        data.put("list", list);
        data.put("total", total);
        return ResponseUtil.ok(data);
    }

    @GetMapping("listQualification")
    public Object listQualification(@LoginAdmin Integer adminId,
                                    @RequestParam(value = "page", defaultValue = "1") Integer page,
                                    @RequestParam(value = "limit", defaultValue = "10") Integer limit,Byte value,String name,String sort, String order) {
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        List<LitemallMechanismVo2> list = mechanismService.queryCheckMechanism(page, limit,value,name, sort, order);

        long total = PageInfo.of(list).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("list", list);
        data.put("total", total);
        return ResponseUtil.ok(data);
    }

    //查询商品详情
    @PostMapping("/showGoods")
    public Object showGoods(@LoginAdmin Integer adminId, @RequestBody LitemallMechanismGoodsCheck goodsCheck){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }
        int goodsId = goodsCheck.getGoodsId();

        LitemallMechanismGoods list = goodsService.findById(goodsId);
        Map<String, Object> data = new HashMap<>();
        data.put("goods", list);
        return ResponseUtil.ok(data);
    }

    /**
     * 批量审核
     */
    @PostMapping("/acceptAllGoods")
    public Object acceptAllGoods(@LoginAdmin Integer adminId,@RequestBody  Map<String, Object> map){
        if(adminId==null){
            return ResponseUtil.unlogin();
        }
        // 是否通过
//        String type = map.get("type")+"";
        if(map.get("ids")!=null){
            String ids= (String) map.get("ids");
            String reson = (String)map.get("reason");
            List<String> result = Arrays.asList(ids.split(","));
            mechanismGoodsCheckService.updateAllByIds(Integer.parseInt(map.get("type").toString()),result,reson);
        }
        if(map.get("goodsIds")!=null){
            String ids= (String) map.get("goodsIds");
            List<String> goodsIds = Arrays.asList(ids.split(","));
            goodsService.updateAllByIds(Integer.parseInt(map.get("type").toString()),goodsIds);
        }
        return ResponseUtil.ok();
    }

    /**
     *  同意审核
     */
    @GetMapping("/acceptGoods")
    public Object acceptGoods(@LoginAdmin Integer adminId,Integer checkId,Integer goodsId) {
        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        try {
            //更新check表
            LitemallMechanismGoodsCheck check = new LitemallMechanismGoodsCheck();
            check.setId(checkId);
            check.setIsCheck((byte)2);
            check.setTransitTime(LocalDateTime.now());
            mechanismGoodsCheckService.updateById(check);
            //更新goods表
            LitemallMechanismGoods goods = new LitemallMechanismGoods();
            goods.setId(goodsId);
            goods.setIsCheck((byte)2);
            goodsService.updateById(goods);
        }catch (Exception ex) {
            txManager.rollback(status);
            logger.error("系统内部错误", ex);
        }
        txManager.commit(status);
        return ResponseUtil.ok();
    }

    /**
    *拒绝审核
     */
    @GetMapping("/refuseGoods")
    public Object refuseGoods(@LoginAdmin Integer adminId, Integer goodsId, Integer checkId,String reason) {
        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        try {
            LitemallMechanismGoodsCheck check = new LitemallMechanismGoodsCheck();
            check.setId(checkId);
            check.setDescribe(reason);
            byte a = 3;
            check.setIsCheck(a);
            LitemallMechanismGoods goods = new LitemallMechanismGoods();
            goods.setId(goodsId);
            goods.setIsCheck(a);
            mechanismGoodsCheckService.updateById(check);
            goodsService.updateById(goods);
        }catch (Exception ex) {
            txManager.rollback(status);
            logger.error("系统内部错误", ex);
        }
        txManager.commit(status);
        return ResponseUtil.ok();
    }
}
